package handler

import (
	"ecomm-mgr/cache"
	"ecomm-mgr/models"
	"ecomm-mgr/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	reids_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, reids_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "错误3次,禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询用户失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, reids_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, reids_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "错误3次,禁言2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	/*SELECT
	*FROM
	roles
	LEFT JOIN user_roles ON user_roles.rid = roles.id
	where user_roles.id=1
	*/
	var roles models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid=?", uid).Debug().
		Find(&roles)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": roles,
	})
	return
}
func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	/*SELECT
	*
		FROM
	nodes
	LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
	WHERE role_nodes.nid=1

	*/
	var nodes models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid=?", rid).Debug().
		Find(&nodes)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": nodes,
	})
	return
}
func GoodsAdd(c *gin.Context) {
	goods_no := c.PostForm("goods_no")
	goods_name := c.PostForm("goods_name")
	goods_type := c.PostForm("goods_type")
	goods_price := c.PostForm("goods_price")
	goods_num, _ := strconv.Atoi(c.PostForm("goods_num"))
	goods_sales, _ := strconv.Atoi(c.PostForm("goods_sales"))

	data := models.Goods{
		GoodsNo:    goods_no,
		GoodsName:  goods_name,
		GoodsType:  goods_type,
		GoodsPrice: goods_price,
		GoodsNum:   goods_num,
		GoodsSales: goods_sales,
	}
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderAdd(c *gin.Context) {
	gid, _ := strconv.Atoi(c.PostForm("gid"))
	order_no := c.PostForm("order_no")
	form_address := c.PostForm("form_address")
	to_address := c.PostForm("to_address")
	data := models.Order{
		OrderNo:     order_no,
		FormAddress: form_address,
		ToAddress:   to_address,
		Gid:         gid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "商品订单添加成功",
		"data": data,
	})
	return
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	/*SELECT
	goods.goods_no as GoodsNO,
		goods.goods_name as GoodsName,
		goods.goods_type as GoodsType,
		goods.goods_price as GoodsPrice,
		goods.goods_num as GoodsNum,
		goods.goods_sales as GoodsSales,
		orders.order_no as OrderNo,
		orders.form_address as FormAddress,
		orders.to_address as ToAddress
	FROM
	orders
	LEFT JOIN goods ON orders.gid=goods.id
	*/
	var goodsOrder []models.GoodsOrder
	redis_key := "Good_List_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Select(
				"orders.order_no as OrderNo",
				"orders.form_address as FormAddress",
				"orders.to_address as ToAddress",
				"goods.goods_name as GoodsName",
				"goods.goods_no as GoodsNo",
				"goods.goods_type as GoodsType",
				"goods.goods_price as GoodsPrice",
				"goods.goods_num as GoodsNum",
				"goods.goods_sales as GoodsSales",
				"goods.id as Gid",
			).
			Joins("LEFT JOIN goods ON orders.gid=goods.id").
			Offset(offset).Limit(size).Debug().Find(&goodsOrder)
		jsonData, _ := json.Marshal(goodsOrder)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &goodsOrder)
	}
	var total int64
	models.DB.Model(&models.Order{}).Debug().Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表展示成功",
		"data":  goodsOrder,
		"total": total,
	})
}
func GoodOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var goodOrderList models.GoodsOrder
	redis_key := "good_list_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Select(
				"goods.goods_name as GoodsName",
				"goods.goods_type as GoodsType",
				"goods.goods_price as GoodsPrice",
				"goods.goods_num as GoodsNum",
				"goods.goods_sales as GoodsSales",
				"orders.order_no as OrderNo",
				"orders.form_address as FormAddress",
				"orders.to_address as ToAddress",
			).
			Joins("LEFT JOIN goods ON orders.gid=goods.id").
			Debug().Find(&goodOrderList)
		jsonData, _ := json.Marshal(goodOrderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &goodOrderList)
	}
	c.JSON(200, gin.H{
		"code": "200",
		"msg":  "商品订单展示成功",
		"data": goodOrderList,
	})
	return
}
